package com.link.speechdemo.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.provider.MediaStore.Audio.Media;
import android.util.Log;


import com.link.speechdemo.bean.LocalMusic;

import java.util.ArrayList;
import java.util.List;

/**
 * 音乐播放工具类
 */

public class MusicUtil {
    private static final String TAG = MusicUtil.class.getSimpleName();
    private static ContentResolver contentResolver;

    /**
     * 获取SD卡所有的音乐
     *
     * @param context
     * @return
     */
    public static List<LocalMusic> getMusic(Context context) {
        List<LocalMusic> olist = null;
        int index = 0;
        contentResolver = context.getContentResolver();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            olist = new ArrayList<>();
            Cursor cursor = contentResolver.query(Media.EXTERNAL_CONTENT_URI, null, null, null, Media.DEFAULT_SORT_ORDER);
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex(Media.TITLE));
                String author = cursor.getString(cursor.getColumnIndex(Media.ARTIST));
                String path = cursor.getString(cursor.getColumnIndex(Media.DATA));
                LocalMusic music = new LocalMusic(index++, name, author, path);
                olist.add(music);
            }

        }
        if (olist.toString().length() > 4000) {
            for (int i = 0; i < olist.toString().length(); i += 4000) {
                if (i + 4000 < olist.toString().length())
                    Log.e("歌曲" + i, olist.toString().substring(i, i + 4000));
                else
                    Log.e("歌曲" + i, olist.toString().substring(i, olist.toString().length()));
            }
        } else
            Log.e("歌曲", olist.toString());
        return olist;
    }

    /**
     * 获取SD卡获取到的第一首歌曲
     *
     * @param context
     * @return
     */
    public static LocalMusic getFirstMusic(Context context) {
        LocalMusic music = new LocalMusic();
        contentResolver = context.getContentResolver();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Cursor cursor = contentResolver.query(Media.EXTERNAL_CONTENT_URI, null, null, null, Media.DEFAULT_SORT_ORDER);
            Log.e(TAG, "getFirstMusic" + cursor);
            if (cursor.moveToFirst()) {
                String name = cursor.getString(cursor.getColumnIndex(Media.TITLE));
                String author = cursor.getString(cursor.getColumnIndex(Media.ARTIST));
                String path = cursor.getString(cursor.getColumnIndex(Media.DATA));
                music.setId(0);
                music.setName(name);
                music.setAuthor(author);
                music.setPath(path);
            }

        }

        Log.e(TAG, "getFirstMusic" + music.toString());
        return music;
    }
}
